package com.nhc.activity_fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Point;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.astrob.NavFrameSDK;
import com.astrob.activitys.DMapActivity;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.Car;
import com.astrob.view.Compass;
import com.astrob.view.MapViewS;
import com.astrob.view.MapViewS.MapCallBack;
import com.astrob.view.ZoomView;
import com.nhc.database.dbmodel.Measure;
import com.nhc.database.dbmodel.MeasurePoint;
import com.nhc.database.manager.MeasureCenter;
import com.nhc.model.MapSetInfo;
import com.nhc.view.MultiMapView;

import org.mapsforge.core.util.MercatorProjection;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.layer.Layer;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.Polygon;
import org.osmdroid.views.overlay.Polyline;

import java.util.ArrayList;
import java.util.List;

import zuo.biao.library.ui.PlacePickerWindow;

import static zuo.biao.library.ui.CutPictureActivity.REQUEST_CODE_CAMERA;

public class MeasureMapActivity extends Activity implements MapCallBack, View.OnClickListener {

    public static final String INTENT_MMAP_MODE = "INTENT_MMAP_MODE";
    public static final String INTENT_MMAP_MID = "INTENT_MMAP_MID";


    public static Intent createIntent(Context context, int mode) {
        return new Intent(context, MeasureMapActivity.class)
                .putExtra(INTENT_MMAP_MODE, mode);
    }

    public static Intent createIntentById(Context context, Long measureId) {
        return new Intent(context, MeasureMapActivity.class)
                .putExtra(INTENT_MMAP_MID, measureId);
    }

    int _mode = 0;//0-测距   1-面积测量
    Long _measureId = 0L;

    ZoomView mZoom;
    TextView mScale;
    TextView tv_measure_info;
    TextView tv_measure_num;
    TextView mLocal;
    TextView tv_areatype;

    MultiMapView mMultiMapView;

    Car mCar = new Car();

    ArrayList<LonLat> mMeasurelist = new ArrayList<LonLat>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.measuremap_activity);

        mMultiMapView = (MultiMapView) findViewById(R.id.id_multimap);
        mMultiMapView.setMapsource(SysUtils.getInstance().mapsource);
        initMapEngin();
        mMultiMapView.mMapViewS.setNeedPopTipInfo(false);

        mZoom = (ZoomView) findViewById(R.id.id_zoomview);
        mScale = (TextView) findViewById(R.id.id_map_scalebar);
        if (SysUtils.getInstance().mapsource != 1000 || SysUtils.getInstance().mapsource != 1001) {
            mScale.setVisibility(View.GONE);
        }
        tv_measure_info = (TextView) findViewById(R.id.tv_measure_info);
        tv_measure_num = (TextView) findViewById(R.id.tv_measure_num);
        tv_areatype = (TextView) findViewById(R.id.tv_areatype);
        tv_areatype.setText("");
        mLocal = (TextView) findViewById(R.id.btnlocal);

        mZoom.setOnClickListener(this);
        mLocal.setOnClickListener(this);

        findViewById(R.id.btn_measure_save).setOnClickListener(this);
        findViewById(R.id.btn_measure_addone).setOnClickListener(this);
        findViewById(R.id.btn_measure_closeone).setOnClickListener(this);
        findViewById(R.id.tv_setting).setOnClickListener(this);

        _mode = getIntent().getIntExtra(INTENT_MMAP_MODE, _mode);
        _measureId = getIntent().getLongExtra(INTENT_MMAP_MID, _measureId);

        LonLat ll = SysUtils.getInstance().getLL();
        mMeasurelist.clear();
        mCar.setFreeMoving(true);

        findViewById(R.id.tv_setting).setVisibility(View.GONE);
        if (_measureId > 0) {
            Measure measure = MeasureCenter.getInstance().getMeasureById(_measureId);
            MeasureCenter.getInstance().measureEdit = measure;
            if (measure != null) {
                if (measure.measurePtList == null || measure.measurePtList.size() < 1) {
                    measure.measurePtList = MeasureCenter.getInstance().getMeasurePointListByMeasureId(_measureId);
                }

                int size = measure.measurePtList.size();
                for (int i = 0; i < size; i++) {
                    mMeasurelist.add(measure.measurePtList.get(i).getLL());
                    if (i == 0) {
                        ll = measure.measurePtList.get(i).getLL();
                    }
                }
                _mode = measure.getType();
                refreshMeasureInfo();
            }
        }

        mCar.navpos_.pos.lon = ll.GetLon();
        mCar.navpos_.pos.lat = ll.GetLat();
        mMultiMapView.setMapOrientation(0);
        mMultiMapView.setScale(50000);
        mMultiMapView.setMapCenter(ll);

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Msg.UPDATEMAP:
                    updateMapView();
                    break;
                case Msg.FINISHUPDATEMAP:
                    finishUpdatedMapView();
                    break;
            }
        }
    };

    private void updateMapView() {
        mMultiMapView.updateMap();
    }

    private void finishUpdatedMapView() {
        if (mMultiMapView.getMapsource() != 1000) {
            mZoom.updateState(0);
        } else {
            mZoom.updateState();
        }
        mScale.setText(mMultiMapView.getScaleString());
    }

    public void onReturnClick(View v) {
        finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                finish();
                break;
            case 24://Zoomin
                if (!SysUtils.getInstance().is240x320) {
                    return true;
                }
                onZoomIn();
                return true;
            case 25://Zoomout
                if (!SysUtils.getInstance().is240x320) {
                    return true;
                }
                onZoomOut();
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnzoomin:
                onZoomIn();
                break;
            case R.id.btnzoomout:
                onZoomOut();
                break;
            case R.id.btnTipcar:
                onTipcar();
                break;
            case R.id.btnTipname:
                onTipname();
                break;
            case R.id.btnTipman:
                onTipman();
                break;
            case R.id.btnlocal:
                onLocal();
                break;
            case R.id.btn_measure_addone:
                measureAddone();
                break;
            case R.id.btn_measure_closeone:
                measureCloseone();
                break;
            case R.id.btn_measure_save:
                measureSave();
                break;
            case R.id.tv_setting:
                measureSetting();
                break;
            default:
                break;
        }
    }

    private void measureSetting() {
        MeasureCenter.getInstance().measureEdit = MeasureCenter.getInstance().getMeasureById(_measureId);
        startActivityForResult(MeasureSettingActivity.createIntent(this), REQUEST_CODE_MPSETTING);
    }

    public static final int REQUEST_CODE_MPSETTING = 18;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_MPSETTING) {
//            double len = 0;
            double area = 0;
            MeasureCenter.getInstance().measureEdit.setLength(Utils.calculateLen(mMeasurelist));
            if (MeasureCenter.getInstance().measureEdit.getAreatype() == 1) {
                area = Utils.calculateAreaByWidth(mMeasurelist, MeasureCenter.getInstance().measureEdit.getWidth());
//                len = Utils.calculateLenAB(mMeasurelist);
                MeasureCenter.getInstance().measureEdit.setAreade(area);
            }
            MeasureCenter.getInstance().saveMeasure(MeasureCenter.getInstance().measureEdit);
            refreshMeasureInfo();
            setResult(RESULT_OK);
        }
    }

    private void measureSave() {
        int size = mMeasurelist.size();
        if (size < 2) {
            Toast.makeText(this, R.string.cldsylgdbbcccl, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        if (_measureId < 1) {
            _measureId = MeasureCenter.getInstance().addNewMeasure();
        }

        Measure measure = MeasureCenter.getInstance().getMeasureById(_measureId);

        //先清空测量上的点
        MeasureCenter.getInstance().removeMeasurePoints(_measureId + "");
        measure.measurePtList.clear();

        for (int i = 0; i < size; i++) {
            LonLat ll = mMeasurelist.get(i);
            MeasureCenter.getInstance().saveMeasurePoint(new MeasurePoint(ll, _measureId));
        }

        measure.setLength(Utils.calculateLen(mMeasurelist));
        if (_mode != 0) {
            measure.setPerimeter(Utils.calculatePerimeter(mMeasurelist));
            measure.setArea(Utils.calculateArea(mMeasurelist));
        }

        measure.setType(_mode);

        double len = 0;
        double area = 0;
        if (measure.getAreatype() == 1) {
            area = Utils.calculateAreaByWidth(mMeasurelist, MeasureCenter.getInstance().measureEdit.getWidth());
//            len = Utils.calculateLenAB(mMeasurelist);
            measure.setAreade(area);
//            measure.setLength(len);//等宽面积，长度
        }

        MeasureCenter.getInstance().saveMeasure(measure);

        setResult(RESULT_OK);
        finish();
    }

    private void measureAddone() {

        LonLat ll = mMultiMapView.getMapCenter();
        if(mMultiMapView.isgcj02) {
            ll = Utils.gcj02towgs84(ll.GetLon(), ll.GetLat());
        }
        mMeasurelist.add(ll);
        refreshMeasureInfo();
        updateMapView();
    }

    private void measureCloseone() {
        int size = mMeasurelist.size();
        if (size < 1)
            return;

        mMeasurelist.remove(size - 1);
        refreshMeasureInfo();
        updateMapView();
    }

    private void refreshMeasureInfo() {

        Measure measureEdit = MeasureCenter.getInstance().measureEdit;

        tv_areatype.setText("");
        if (_mode == 0) {
            double len = Utils.calculateLen(mMeasurelist);
            String DIS[] = SysUtils.getInstance().getDistanceStr((int) len);
            tv_measure_info.setText(getString(R.string.juli_t) + DIS[0] + DIS[1]);

        } else if (_mode == 1) {

            double perimeter = Utils.calculatePerimeter(mMeasurelist);//周长
            double area = Utils.calculateArea(mMeasurelist);
            double len = Utils.calculateLen(mMeasurelist);

            String areatype = "";
            if (measureEdit != null) {
//                findViewById(R.id.tv_setting).setVisibility(View.VISIBLE);
                switch (measureEdit.getAreatype()) {
                    default:
                        area = Utils.calculateArea(mMeasurelist);
                        break;
                    case 1:
                        areatype = "[" + getString(R.string.dkmjcl) + "]";
                        area = Utils.calculateAreaByWidth(mMeasurelist, measureEdit.getWidth());
                        measureEdit.setLength(len);
                        break;
                    case 2:
                        areatype = "[" + getString(R.string.pmcl) + "]";
                        area = Utils.calculateArea(mMeasurelist);
                        double aa = Math.cos(measureEdit.getSlopeangle());
                        if (aa != 0) {
                            area /= aa;
                        }
                        if (area < 0) {
                            area = -area;
                        }
                        break;
                }
            }

            tv_areatype.setText(areatype);
            String AREA[] = SysUtils.getInstance().getAreaStr(area);
            String DIS[] = SysUtils.getInstance().getDistanceStr((int) perimeter);
            String DIS2[] = SysUtils.getInstance().getDistanceStr((int) len);
            if (measureEdit != null && measureEdit.getAreatype() == 1) {
                tv_measure_info.setText("长度：" + DIS2[0] + DIS2[1] + "\n" + getString(R.string.mianji_t) + AREA[0] + AREA[1]);
            } else {
                tv_measure_info.setText(getString(R.string.zhouchang_t) + DIS[0] + DIS[1] + "\n" + getString(R.string.mianji_t) + AREA[0] + AREA[1]);
            }

        }

        tv_measure_num.setText(mMeasurelist.size() + " 个");

        Start.getInstance().MapKit().clearPoly();

        if (_mode == 1) {
            //只是画面的时候使用,app目前只有在测量记录里有画Area
//            addArea2TME();
        }
    }

    void addArea2TME2() {
        //这样是可以的
        //死机原因，在接口里new 的对象太大导致死机。---jni不死了，可以不用了
        int size = mMeasurelist.size();
        if (size > 2) {
            int color = Color.rgb(0, 0, 222);
            int max = 200;
            if (size < max) {
                max = size;
            }
            NavFrameSDK.CLonLat lls[] = new NavFrameSDK.CLonLat[max];
            int j = 0;
            for (int i = 0; i < size; i++) {
                LonLat ll = mMeasurelist.get(i);
                lls[j] = NavFrameSDK.getInstance().new CLonLat();
                lls[j].lon = ll.GetLon();
                lls[j].lat = ll.GetLat();
                j++;
                if (j == max) {
                    Start.getInstance().MapKit().addPoly(lls, 0, color, 4, _mode);
                    max = size - i - 1;
                    if (max < 3) {
                        break;
                    }
                    lls = new NavFrameSDK.CLonLat[max];
                    j = 0;
                }
            }
        }

        //地图强刷
        Start.getInstance().MapKit().moveMap(0, 0);
    }

    void addArea2TME() {
        int size = mMeasurelist.size();

        if (size <= 2)
            return;
        if (SysUtils.getInstance().mapsource == 1000) {
            NavFrameSDK.CLonLat lls[] = new NavFrameSDK.CLonLat[size];
            for (int i = 0; i < size; i++) {
                LonLat ll = mMeasurelist.get(i);
                lls[i] = NavFrameSDK.getInstance().new CLonLat();
                lls[i].lon = ll.GetLon();
                lls[i].lat = ll.GetLat();
            }
            int color = Color.parseColor("#AA0000FF");//透明无效，rgb对应引擎bgr
            Start.getInstance().MapKit().addPoly(lls, 0, color, 4, _mode);
            //地图强刷
            Start.getInstance().MapKit().moveMap(0, 0);

            //函数时间test
            long A = SystemClock.uptimeMillis();

            long E = SystemClock.uptimeMillis();
            Long x = E - A;
        } else if (SysUtils.getInstance().mapsource == 1001) {

        } else {

        }
    }

    void onZoomIn() {
        mMultiMapView.zoomIn();
        mMultiMapView.updateMap();
    }

    void onZoomOut() {
        mMultiMapView.zoomOut();
        mMultiMapView.updateMap();
    }

    void onLocal() {
        if (Utils.isFastDoubleClick())
            return;
        LonLat ll = SysUtils.getInstance().getLL();
        mCar.navpos_.pos.lon = ll.GetLon();
        mCar.navpos_.pos.lat = ll.GetLat();
        mMultiMapView.setMapCenter(mCar.getCarLL());
        mMultiMapView.setScale(100000);
        mMultiMapView.updateMap();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            default:
                break;
            case 21://left
                mMultiMapView.moveMap(-5, 0);
                return true;
            case 22://right
                mMultiMapView.moveMap(5, 0);
                return true;
            case 19://up
                mMultiMapView.moveMap(0, -5);
                return true;
            case 20://down
                mMultiMapView.moveMap(0, 5);
                return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    void onTipcar() {
        if (Utils.isFastDoubleClick())
            return;
    }

    void onTipname() {
        if (Utils.isFastDoubleClick())
            return;
    }

    void onTipman() {
        if (Utils.isFastDoubleClick())
            return;
    }

    @Override
    public void popTipInfo(NavFrameSDK.POIDescription data) {
    }

    @Override
    public void moveMap(boolean removeTip) {
    }

    @Override
    public void touchUp() {

    }

    @Override
    public void longPress(LonLat ll) {
    }

    @Override
    public void doubleClick(LonLat ll) {
    }

    @Override
    public void singleClick(LonLat ll, Point tipPoint) {

    }

    Compass mCompass = new Compass();

    @Override
    public void drawOverlay(Canvas canvas, float ws) {

        if (mMultiMapView.getMapsource() != 1000) {
            return;
        }

        MapSetInfo.getInstance().draw(this, canvas, ws, mMultiMapView.mMapViewS);

        if (_measureId == 0) {
            mCar.setMapsize(mMultiMapView.mMapViewS._mapWidth, mMultiMapView.mMapViewS._mapHeight);
            mCar.draw(this, canvas, ws, ws);
        }

        mCompass.draw(this, canvas, ws, ws);

        drawMeasure(canvas, ws);//测量

        //画完图
        mHandler.sendEmptyMessage(Msg.FINISHUPDATEMAP);
    }

    //无裁剪，50米的比例尺面显示不全
    private void drawMeasure(Canvas canvas, float ws) {
        int count = mMeasurelist.size();
        if (count < 1) {
            return;
        }

        ArrayList<Point> pointlist = new ArrayList<Point>();
        for (int i = 0; i < count; ++i) {
            LonLat poiLL = mMeasurelist.get(i);
            poiLL = Utils.wgs84togcj02(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
            Point e = Start.getInstance().MapKit().LL2XY(poiLL);
            pointlist.add(e);
        }

        Paint paint = new Paint();
        paint.reset();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(4);
        paint.setColor(Color.parseColor("#AA0000FF"));
        paint.setAntiAlias(true);
        PathEffect pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
        paint.setPathEffect(pathEffect);
        Path path = new Path();

        if (count >= 2) {
            Point ff = pointlist.get(0);
            path.moveTo(ff.x * ws, ff.y * ws);
            for (int i = 1; i < count; ++i) {
                ff = pointlist.get(i);
                path.lineTo(ff.x * ws, ff.y * ws);
            }

            if (_mode == 1) {
                path.close();//封闭
            }

            canvas.drawPath(path, paint);

            if (_mode == 1) {
                //画面用引擎画吧
                paint.setColor(Color.parseColor("#880000FF"));
                paint.setStyle(Paint.Style.FILL);
                canvas.drawPath(path, paint);
            }
        }

        if (Start.getInstance().MapKit().getScale() > 1000) {
            //小比例尺不显示
            for (int i = 0; i < count; ++i) {
                Point ff = pointlist.get(i);
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.parseColor("#AAFF0000"));
                canvas.drawCircle(ff.x * ws, ff.y * ws, dip2px(12), paint);

                String strPrn = (i + 1) + "";
                float textWidth = paint.measureText(strPrn) / 2;
                float textHeight = paint.getTextSize() / 2;
                paint.setColor(Color.WHITE);
                paint.setTextSize(13);
                paint.setFakeBoldText(true);
                canvas.drawText(strPrn, ff.x * ws - textWidth, ff.y * ws + textHeight - 1,
                        paint);
            }
        }


    }

    private void drawMeasure2(Canvas canvas, float ws) {
        int count = mMeasurelist.size();
        if (count < 1) {
            return;
        }

        int w = mMultiMapView.mMapViewS._mapWidth;
        int h = mMultiMapView.mMapViewS._mapHeight;

        PointF lt = null;//左上点如果不在多边形内则为null
        PointF rt = null;
        PointF rb = null;
        PointF lb = null;

        if (mMultiMapView.mMapViewS.llRect.size() == 4) {
            if (Utils.pointInPolygonforLL(mMultiMapView.mMapViewS.llRect.get(0), mMeasurelist)) {
                lt = new PointF(0f, 0f);
            }

            if (Utils.pointInPolygonforLL(mMultiMapView.mMapViewS.llRect.get(1), mMeasurelist)) {
                rt = new PointF((float) w, 0f);
            }

            if (Utils.pointInPolygonforLL(mMultiMapView.mMapViewS.llRect.get(2), mMeasurelist)) {
                rb = new PointF((float) w, (float) h);
            }

            if (Utils.pointInPolygonforLL(mMultiMapView.mMapViewS.llRect.get(3), mMeasurelist)) {
                lb = new PointF(0f, (float) h);
            }
        }

        Paint paint = new Paint();
        paint.reset();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(4);
        paint.setColor(Color.parseColor("#AA0000FF"));
        paint.setAntiAlias(true);
        PathEffect pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
        paint.setPathEffect(pathEffect);
        Path path = new Path();

        List<PointF> pointList = new ArrayList<PointF>();

        if (count >= 2) {
            Point AA = null;
            int ii = -1;
            for (int i = 1; i <= count; ++i) {
                LonLat poiLLA = null;
                LonLat poiLLB = null;
                if (i == count) {
                    if (_mode == 1) {
                        poiLLA = mMeasurelist.get(count - 1);
                        poiLLB = mMeasurelist.get(0);
                    } else {
                        break;
                    }
                } else {
                    poiLLA = mMeasurelist.get(i - 1);
                    poiLLB = mMeasurelist.get(i);
                }

                double[] lineLL = {poiLLA.GetLon(), poiLLA.GetLat(), poiLLB.GetLon(), poiLLB.GetLat()};
                if (!Utils.isLineIntersectRectangle(mMultiMapView.mMapViewS.getMapRegion(), lineLL)) {
                    continue;
                }

                Point A = null;
                if (AA != null && ii == i - 1) {
                    A = AA;
                } else {
                    A = Start.getInstance().MapKit().LL2XY(poiLLA);//耗时操作能省则省
                }
                Point B = Start.getInstance().MapKit().LL2XY(poiLLB);
                AA = B;
                ii = i;

                int[] line = {A.x, A.y, B.x, B.y};
                if (Utils.revisePt(line, w, h)) {
                    path.moveTo(line[0] * ws, line[1] * ws);
                    path.lineTo(line[2] * ws, line[3] * ws);

                    int num = pointList.size();
                    PointF P1 = new PointF(line[0], line[1]);
                    PointF P2 = new PointF(line[2], line[3]);
                    PointF P0 = null;
                    if (num > 1) {
                        P0 = pointList.get(num - 1);
                    }
                    if (P0 == null || !P0.equals(P1)) {
                        pointList.add(P1);
                    }
                    pointList.add(P2);
                }
            }

            if (_mode == 1) {
//                path.close();//封闭
                paint.setColor(Color.LTGRAY);
            }

            canvas.drawPath(path, paint);

            int size = pointList.size();
            if (_mode == 1) {
                List<PointF> pointListE = new ArrayList<PointF>();
                if (size > 2) {
                    //屏幕内如果有点至少是3个点
                    for (int i = 1; i < size; i++) {
                        PointF A0 = pointList.get(i - 1);
                        PointF A1 = pointList.get(i);
                        pointListE.add(A0);

                        int indexA0 = edgeNumber(A0);//A0是否在边上
                        int indexA1 = edgeNumber(A1);//A1是否在边上
                        if (indexA0 > 0 && indexA1 > 0 && indexA0 != indexA1) {
                            //两个相邻的点，在两个不同的边上，则加入有效的屏幕端点
                            if (lt != null) {
                                pointListE.add(lt);
                            }
                            if (rt != null) {
                                pointListE.add(rt);
                            }
                            if (rb != null) {
                                pointListE.add(rb);
                            }
                            if (lb != null) {
                                pointListE.add(lb);
                            }
                        }
                        pointListE.add(A1);
                    }
                } else if (lt != null && rt != null && rb != null && lb != null) {
                    //多边形包含屏幕
                    pointListE.add(lt);
                    pointListE.add(rt);
                    pointListE.add(rb);
                    pointListE.add(lb);
                }

                pointList.clear();
                PointF lastA = null;
                //过滤相邻重复的点
                for (int i = 0; i < pointListE.size(); i++) {
                    PointF Z = pointListE.get(i);
                    if (lastA != null && lastA.equals(Z)) {
                        continue;
                    }
                    pointList.add(Z);
                    lastA = Z;
                }

                size = pointList.size();
                if (size > 2) {
                    Path path2 = new Path();
                    path2.moveTo(pointList.get(0).x * ws, pointList.get(0).y * ws);
                    for (int i = 1; i < size; i++) {
                        path2.lineTo(pointList.get(i).x * ws, pointList.get(i).y * ws);
                    }
                    //path2.close();//封闭
                    paint.setColor(Color.parseColor("#AAFF0000"));
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawPath(path2, paint);
                }
            }
        }

        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(13);
        paint.setFakeBoldText(true);
        for (int i = 0; i < count; ++i) {
            LonLat poiLL = mMeasurelist.get(i);
            if (!mMultiMapView.mMapViewS.isInMapRegion(poiLL)) {
                continue;
            }
            Point ff = Start.getInstance().MapKit().LL2XY(poiLL);

            paint.setColor(Color.parseColor("#AAFF0000"));
            canvas.drawCircle(ff.x * ws, ff.y * ws, dip2px(12), paint);

            String strPrn = (i + 1) + "";
            float textWidth = paint.measureText(strPrn) / 2;
            float textHeight = paint.getTextSize() / 2;
            paint.setColor(Color.WHITE);
            canvas.drawText(strPrn, ff.x * ws - textWidth, ff.y * ws + textHeight - 1,
                    paint);
        }

    }

    //1 - 上边 2- 右边 3-下边 4-左边
    private int edgeNumber(PointF A) {
        int w = mMultiMapView.mMapViewS._mapWidth;
        int h = mMultiMapView.mMapViewS._mapHeight;

        if (A.x == 0) {
            return 4;
        } else if (A.y == 0) {
            return 1;
        } else if (A.x == w) {
            return 2;
        } else if (A.y == h) {
            return 3;
        }

        return -1;
    }

    @Override
    public void onDestroy() {
        mMeasurelist.clear();
        Start.getInstance().MapKit().clearPoly();
        mMultiMapView.destroyMap();
        super.onDestroy();
    }

    //====================
    private void initMapEngin() {

        if (mMultiMapView.getMapsource() == 1001) {
            mMultiMapView.mapView.addLayer(mapsforgeLayer);
        } else if (mMultiMapView.getMapsource() != 1000) {
            mGisOverlay = new CustomPointOverlay();
            mMultiMapView.mMapViewOnline.getOverlays().add(mGisOverlay);
        }

        mMultiMapView.setMapCallback(this, mapListener);
    }

    //======OSM
    MapListener mapListener = new MapListener() {
        @Override
        public boolean onScroll(ScrollEvent scrollEvent) {

            return true;
        }

        @Override
        public boolean onZoom(ZoomEvent zoomEvent) {
            return false;
        }

        @Override
        public void longPress(Point pt) {
            if (pt == null) {
                return;
            }
        }

        //双击
        @Override
        public void doubleClick(Point pt) {
            if (pt == null) {
                return;
            }
        }

        //单击 单击后
        @Override
        public void singleClick(Point pt) {
            if (pt == null) {
                return;
            }
        }

        //移图后抬起
        @Override
        public void touchUp() {
        }

        //手指移动-切换到移图模式
        @Override
        public void moveMap() {
        }

    };

    private CustomPointOverlay mGisOverlay = null;

    public class CustomPointOverlay extends Overlay {

        private final Point mMapCoordsProjected = new Point();

        public CustomPointOverlay() {
        }

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {

            if (mMultiMapView.getMapsource() >= 1000 && mMultiMapView.getMapsource() <= 1001) {
                return;
            }

            MapSetInfo.getInstance().draw2(MeasureMapActivity.this, canvas, mapView);

            mCompass.draw2(MeasureMapActivity.this, canvas, (int) mapView.getMapOrientation());

            if (_measureId == 0) {
                mCar.setMapsize(canvas.getWidth(), canvas.getHeight());
                mCar.draw2(MeasureMapActivity.this, canvas, mapView, mMultiMapView.isgcj02);//ok
            }

            drawMeasure2(canvas, mapView, shadow);//测量

            //画完图
            mHandler.sendEmptyMessage(Msg.FINISHUPDATEMAP);

        }

        //经纬度坐标到屏幕坐标的转换
        Point LL2XY(LonLat ll) {
            Point B = new Point();
            mMultiMapView.mMapViewOnline.getProjection().toProjectedPixels(ll.GetLat(),
                    ll.GetLon(), mMapCoordsProjected);
            Projection pj = mMultiMapView.mMapViewOnline.getProjection();
            pj.toPixelsFromProjected(mMapCoordsProjected, B);
            return B;
        }

        void drawMeasure2(Canvas canvas, MapView mapView, boolean shadow) {
            int count = mMeasurelist.size();
            if (count < 1) {
                return;
            }

            List<GeoPoint> points = new ArrayList<>();
            List<Point> ptlist = new ArrayList<>();
            for (int i = 0; i < count; ++i) {
                LonLat poiLL = mMeasurelist.get(i);
                if (mMultiMapView.isgcj02) {
                    poiLL = Utils.wgs84togcj02(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
                }
                points.add(new GeoPoint(poiLL.GetLat(), poiLL.GetLon()));

                Point ff = LL2XY(poiLL);
                ptlist.add(ff);
            }

            if (_mode == 1) {
                //面积
                Polygon polygon = new Polygon();
                Paint paint = polygon.getOutlinePaint();
                paint.reset();
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(4);
                paint.setColor(Color.parseColor("#AA0000FF"));
                paint.setAntiAlias(true);
                PathEffect pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
                paint.setPathEffect(pathEffect);

                polygon.setFillColor(Color.parseColor("#880000FF"));

                polygon.setPoints(points);
                polygon.draw(canvas, mapView, shadow);
            } else {
                Polyline routeline = new Polyline();

                routeline.setPoints(points);

                Paint paint = routeline.getPaint();
                paint.reset();
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(4);
                paint.setColor(Color.parseColor("#AA0000FF"));
                paint.setAntiAlias(true);
                PathEffect pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
                paint.setPathEffect(pathEffect);
                routeline.draw(canvas, mapView, shadow);
            }

            int sale = mapView.getZoomLevel(false);
            if (sale < 13) {
                return;
            }

            Paint paint = new Paint();
            for (int i = 0; i < count; ++i) {
                Point ff = ptlist.get(i);
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.parseColor("#AAFF0000"));
                canvas.drawCircle(ff.x, ff.y, dip2px(12), paint);

                String strPrn = (i + 1) + "";
                float textWidth = paint.measureText(strPrn) / 2;
                float textHeight = paint.getTextSize() / 2;
                paint.setColor(Color.WHITE);
                paint.setTextSize(13);
                paint.setFakeBoldText(true);
                canvas.drawText(strPrn, ff.x - textWidth, ff.y + textHeight - 1,
                        paint);
            }

        }

    }

    int dip2px(int dip) {
        return Utils.dip2px(this, dip);
    }

    //======Mapsforge
    MapsforgeLayer mapsforgeLayer = new MapsforgeLayer();

    public class MapsforgeLayer extends Layer {

        org.mapsforge.core.model.BoundingBox bb;
        byte zoomLevel;
        org.mapsforge.core.graphics.Canvas canvas;
        org.mapsforge.core.model.Point topLeftPoint;

        public MapsforgeLayer() {
        }

        @Override
        public synchronized void draw(org.mapsforge.core.model.BoundingBox bb, byte zoomLevel, org.mapsforge.core.graphics.Canvas canvas, org.mapsforge.core.model.Point topLeftPoint) {

            if (mMultiMapView.getMapsource() != 1001) {
                return;
            }

            this.bb = bb;
            this.zoomLevel = zoomLevel;
            this.canvas = canvas;
            this.topLeftPoint = topLeftPoint;

            MapSetInfo.getInstance().draw3(MeasureMapActivity.this, canvas, bb, zoomLevel, topLeftPoint, displayModel);
            mCompass.draw3(MeasureMapActivity.this, canvas, 0, bb, zoomLevel, topLeftPoint, displayModel);
            android.graphics.Canvas androidCanvas = AndroidGraphicFactory.getCanvas(canvas);


            if (_measureId == 0) {
                mCar.setMapsize(canvas.getWidth(), canvas.getHeight());
                mCar.draw3(MeasureMapActivity.this, canvas, bb, zoomLevel, topLeftPoint, displayModel);//ok
            }

            drawMeasure3(androidCanvas);//测量

            //画完图
            mHandler.sendEmptyMessage(Msg.FINISHUPDATEMAP);
        }

        //经纬度坐标到屏幕坐标的转换
        Point LL2XY(LonLat ll) {
            long mapSize = MercatorProjection.getMapSize(zoomLevel, displayModel.getTileSize());
            int x = (int) (MercatorProjection.longitudeToPixelX(ll.GetLon(), mapSize) - topLeftPoint.x);
            int y = (int) (MercatorProjection.latitudeToPixelY(ll.GetLat(), mapSize) - topLeftPoint.y);
            Point B = new Point(x, y);
            return B;
        }

        void drawMeasure3(Canvas canvas) {
            int count = mMeasurelist.size();
            if (count < 1) {
                return;
            }

            ArrayList<Point> pointlist = new ArrayList<Point>();
            for (int i = 0; i < count; ++i) {
                LonLat poiLL = mMeasurelist.get(i);
                Point e = LL2XY(poiLL);
                pointlist.add(e);
            }

            Paint paint = new Paint();
            paint.reset();
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(4);
            paint.setColor(Color.parseColor("#AA0000FF"));
            paint.setAntiAlias(true);
            PathEffect pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
            paint.setPathEffect(pathEffect);
            Path path = new Path();

            if (count >= 2) {
                Point ff = pointlist.get(0);
                path.moveTo(ff.x, ff.y);
                for (int i = 1; i < count; ++i) {
                    ff = pointlist.get(i);
                    path.lineTo(ff.x, ff.y);
                }

                if (_mode == 1) {
                    path.close();//封闭
                }

                canvas.drawPath(path, paint);

                if (_mode == 1) {
                    paint.setColor(Color.parseColor("#880000FF"));
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawPath(path, paint);
                }

            }

            byte sale = mMultiMapView.mapView.getModel().mapViewPosition.getZoomLevel();
            if (sale < 13) {
                return;
            }

            for (int i = 0; i < count; ++i) {
                Point ff = pointlist.get(i);
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.parseColor("#AAFF0000"));
                canvas.drawCircle(ff.x, ff.y, dip2px(12), paint);

                String strPrn = (i + 1) + "";
                float textWidth = paint.measureText(strPrn) / 2;
                float textHeight = paint.getTextSize() / 2;
                paint.setColor(Color.WHITE);
                paint.setTextSize(13);
                paint.setFakeBoldText(true);
                canvas.drawText(strPrn, ff.x - textWidth, ff.y + textHeight - 1,
                        paint);
            }

        }

    }
}
